<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入昵称进行搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <rrOperation/>
          </div>
          <crudOperation show="" :permission="permission"/>

  </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                   :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
          <el-form ref="form"  :model="form" :rules="rules"  label-width="80px">
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="学校名称" prop="name">
                    <el-input v-model="form.name"/>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="状态" prop="type">
                    <el-radio-group v-model="form.tenantType">
                      <el-radio v-model="form.tenantType" :label="0">全日制</el-radio>
                      <el-radio v-model="form.tenantType" :label="1">半日制</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="学校地址" prop="address">
              <avue-map v-model="text" style="width:100%"></avue-map>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;"
                  @selection-change="crud.selectionChangeHandler" >
          <el-table-column :selectable="checkboxT" type="selection" width="55"/>
          <el-table-column align="center" :show-overflow-tooltip="true" prop="name" label="学校名称" />
          <el-table-column  align="center":show-overflow-tooltip="true" prop="type" label="学校类型">
            <template slot-scope="scope">
              <span v-if="scope.row.type=1">全日制</span>
              <span  v-if="scope.row.type=0">半日制</span>
            </template>
          </el-table-column>
          <el-table-column  align="center":show-overflow-tooltip="true" prop="province" label="省"/>
          <el-table-column  align="center" :show-overflow-tooltip="true" prop="city" label="市"/>
          <el-table-column align="center" :show-overflow-tooltip="true" prop="area" label="区"/>
          <el-table-column align="center" :show-overflow-tooltip="true" prop="address" label="学校地址"/>
          <el-table-column align="center" :show-overflow-tooltip="true" prop="createTime" width="135" label="创建日期">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-permission="['admin','user:edit','user:del']"
            label="操作"
            width="250"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                style="display: inline-block"
                :data="scope.row"
                :permission="permission"
                :disabled-dle="scope.row.id === user.id"
              />
              <el-button
                style="display: inline-block;"
                :permission="permission"
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="bindDepartment(scope.row)">
                选择院系
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination/>
      </el-col>
    </el-row>


    <!-- 绑定院系 start-->
    <el-dialog title="选择院系" :visible.sync="showBinding" width="30%" :destroy-on-close="true" :before-close="clearData">
      <el-form :model="departmentForm">
        <el-form-item label="请选择内容" label-width="120px">
          <el-cascader :props="props" v-model="departmentForm.department" :options="departmentList" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clickSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 绑定院系 end-->
  </div>
</template>

<script>
import crudTenant from '@/api/system/tenant'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Treeselect from '@riophae/vue-treeselect'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import appUtils from '@/utils/appUtils'
import { getToken } from '@/utils/auth'
import dataUtils from '@/utils/dataUtils'
import {getDepartments,bindData} from '@/api/system/tenant'

let userRoles = []
const defaultForm = {
  name: null,
  id: null,
  address:null,
  tenantType:0,
  province:null,
  provinceNumber:null,
  city:null,
  cityNumber:null,
  area:null,
  areaNumber:null
}
export default {
  name: 'School',
  components: { Treeselect, crudOperation, rrOperation, udOperation, pagination, DateRangePicker },
  cruds() {
    return CRUD({ title: '学校', url: 'admin/SysTenant/page', exportUrl:'admin/sysUser/export-user-list',crudMethod: { ...crudTenant } })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  data() {
    return {
      // 绑定院系
      showBinding:false,
      props: { multiple: true },
      /* map地址*/
      text: {},
      /*下载路径*/
      path: process.env.BASE_URL,
      /*上传文件的列表*/
      fileList:[],
      headers: {
        'Authorization': getToken()
      },
      showUpload: false,
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '',  level: 3,
      roles: [],
      roleIdList: [], // 多选时使用
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: [ 'sys_tenant_view'],
        edit: [ 'sys_tenant_view'],
        del: [ 'sys_tenant_view']
      },
      enabledTypeOptions: [
        { key: 'false', display_name: '未冻结' },
        { key: 'true', display_name: '冻结' }
      ],
      rules: {
        name: [
          { required: true, message: '请输入用户真是姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 院系数据
      departmentList:[],
      departmentForm:{
        department:null
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'minioApi',
      'updateAvatarApi',
      'baseApi'
    ])
  },
  created() {

  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    /*删除上传文件*/
    fileRemove(file, fileList){

    },
    /*文件上传之前*/
    beforeUpload(file){
      crud.downloadLoading=true
      /*限定导入格式*/
        let format=(file.name).substring(file.name.lastIndexOf("."),file.name.length)
      if (format!=='xlsx'){
        appUtils.showError("上传错误，只能上传.xlsx格式的文件")
        return false;
      }
    },
    /*文件上传成功之后*/
    uploadSuccess(res, file, fileList){
      crud.downloadLoading=true
      if (res.state){
        appUtils.showSuccess("导入成功,未导入数据："+res.data.errorList.length+"条")
        this.fileList=[]
        this.crud.refresh()
      }
      else {
        this.fileList=[]
        appUtils.showError(res.msg)
      }
    },
    /*文件上传失败*/
    uploadError(err, file, fileList){
      crud.downloadLoading=true
      appUtils.showError(err.msg)
      this.fileList=[]
    },
    // 学校绑定院系
    bindDepartment(data){
      this.showBinding=true
      this.departmentForm.department=null
      dataUtils.setData("tenantId",data.id)
      let that=this
      this.departmentList=[]
      getDepartments().then(res=>{
        if (res.state){
          // 展示其他数据
          let total=res.data.totalData
          total.forEach(function(element) {
            let list=[]
            if (element.majorList.length>0){
              element.majorList.forEach(function(element){
                let data={
                  value:element.id,
                  label:element.name
                }
                list.push(data)
              })
            }
            let data={
              value:element.id,
              label:element.name,
              children:list
            }
            that.departmentList.push(data)
          })
        }
      })
    },
    clearData(done){
      this.departmentForm.department=null
      done()
    },
    clickSubmit(){
      let tenantDepartmentList=[]
      if (this.departmentForm.department.length>0){
        this.departmentForm.department.forEach(function(val){
          let tenant={
            tenantId:dataUtils.getData("tenantId"),
            departmentId:val[0],
            majorId:val[1]
          }
          tenantDepartmentList.push(tenant)
        })
        bindData(tenantDepartmentList).then(res=>{
          if (res.state){
            appUtils.showSuccess(res.msg)
          }
          else {
            appUtils.showError(res.msg)
          }
        })
      }
      dataUtils.removeData("tenantId")
      this.showBinding=false
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.roleIdList = []
    },
    [CRUD.HOOK.beforeToCU](crud) {
      this.text={}
      console.log('数据',crud.form)
      defaultForm.tenantType=crud.form.type
      this.text.formattedAddress=crud.form.address
    },
    /*提交之前处理数据*/
    [CRUD.HOOK.afterValidateCU](crud) {
      crud.form.type=crud.form.tenantType
      if (this.text.formattedAddress!=null){
        crud.form.address=this.text.formattedAddress
        crud.form.cityNumber=Number(this.text.addressComponent.adcode)
        crud.form.provinceNumber=Number(this.text.addressComponent.citycode)
        crud.form.areaNumber=Number(this.text.addressComponent.streetNumber)
        crud.form.province=this.text.addressComponent.province
        crud.form.city=this.text.addressComponent.city
        if (crud.form.city==null){
          crud.form.city=this.text.addressComponent.province
        }
        crud.form.area=this.text.addressComponent.district
      }
      else {
        appUtils.showError("请选择学校地址")
        return false
      }

    },
    checkboxT(row, rowIndex) {

    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
